<?php
include("../UserIncludes/DbConfig.php");
$mdid=$_REQUEST['advertiseid'];

// $mdid='093f65e080a295f8076b1c5722a46aa2';
// $mdid='32bb90e8976aab5298d5da10fe66f21d';
// $mdid='d2ddea18f00665ce8623e36bd4e3c7c5';
// $mdid='c4ca4238a0b923820dcc509a6f75849b'; // 1
if($mdid=='')$mdid='c4ca4238a0b923820dcc509a6f75849b'; // For debug


$path_offset="/admobweb_new/";
$path="http://".$_SERVER['HTTP_HOST'];
$path=$path.$path_offset;

//$SQL="SELECT AP.`adspaceId`, AP.`adsiteId`, `AS`.`ctr_grade` FROM `adsite_master` `AS`,`adspace_master` AP WHERE `AS`.`adsiteId`=AP.`adsiteId` AND AP.`adspaceIdMd`='".$mdid."' AND AP.`status`='Y'";
$SQL_main="SELECT AP.`adspaceId`, AP.`adsiteId`, `AS`.`ctr_grade`, AD.* FROM `adsite_master` `AS`,`adspace_master` AP, `adspace_details` AD WHERE AD.`adspaceId`=AP.`adspaceId` AND `AS`.`adsiteId`=AP.`adsiteId` AND AP.`adspaceIdMd`='".$mdid."' AND AP.`status`='Y'";
$RS_main=mysql_query($SQL_main) or die("Error #val");
if(mysql_num_rows($RS_main)){
$ROW_main=mysql_fetch_array($RS_main) or die("Error #val2");
$sp=$ROW_main['adspaceId'];  // adspace id
$ctr_grade=$ROW_main[ctr_grade];  // Site's CTR grade (A,B,C,D,E)
#######################################



    $cellSpacing = 6;
    $cellPadding = 6;
    $rows = 1;
    $cols = 1;
    $sizes =explode("x", $ROW[adSize]);
    $totalWidth = $sizes[0];
    $totalHeight = $sizes[1];

    switch ($ROW_main[adSize]) {
        case "184x360" :
            $adsno = 5;
            $rows = 5;
            $descriptionFontSize = "12px";
            break;
        case "468x60" :
            $adsno = 2;
            $cellSpacing = 6;
            $alignment = "horizontal";
            $cols = 2;
            $titleFontSize = "12px";
            $descriptionFontSize = "11px";
            break;
        case "234x60" :
            $adsno = 1;
            $cellSpacing = 6;
            $titleFontSize = "12px";
            $descriptionFontSize = "12px";
            break;
        case "728x90" :
            $adsno = 5;
            $alignment = "horizontal";
            $cols = 5;
            $descriptionFontSize = "12px";
            break;
        case "125x125" :
            $adsno = 1;
            $cellSpacing = 0;
            $titleFontSize = "12px";
            $descriptionFontSize = "12px";
            break;
        case "120x240" :
            $adsno = 3;
            $rows = 3;
            $titleFontSize = "12px";
            $descriptionFontSize = "12px";
            break;
        case "180x150" :
            $adsno = 1;
            $titleFontSize = "12px";
            $descriptionFontSize = "12px";
            break;
        case "300x250" :
            $adsno = 4;
            $cols = 2;
            $rows = 2;
            break;
        case "336x280" :
            $adsno = 6;
            $cols = 3;
            $rows = 2;
            break;
        case "250x250" :
            $adsno = 4;
            $cols = 2;
            $rows = 2;
            break;
        case "120x600" :
            $adsno = 6;
            $rows = 6;
            break;
        case "160x600" :
            $adsno = 7;
            $rows = 7;
            break;
        default :
            $adsno =$ROW_main[noOfTextAd];
            $cellSpacing = 6;
            $alignment =strtolower($ROW_main[thumbOrientation]);
            if($alignment=='horizontal')$cols =$adsno;
            else $rows = $adsno;
            $width = $sizes[0];
            $height = $sizes[1];
            $totalWidth =$width*$cols;
            $totalHeight = $height*$rows;
            break;
    }
   //echo "Cols: ".$cols." Rows: ".$rows." Adsno: ".$adsno."<br>";
    
    if($ROW_main[fontType]!=""){
    $fontType=$ROW_main[fontType];
    }else{
    $fontType="Arial";
    }
    if($ROW_main[backgroundColor]!=""){
    $backgroundColor=$ROW_main[backgroundColor];
    }else{
    $backgroundColor="#E8E8E8";
    }
    //echo $backgroundColor;
    if($ROW_main[headerColor]!=""){
    $headerColor=$ROW_main[headerColor];
    }else{
    $headerColor="#E8E8E8";
    }
    //echo $headerColor;
    if($ROW_main[bodyColor]!=""){
    $bodyColor=$ROW_main[bodyColor];
    }else{
    $bodyColor="#000000";
    }
$c=0;
$r=0;

####################################
}else die("Blocked");
# First check the adsite has been passed the filter or not --- `site_approval_map`, `approval_filter`

$nets=array(); // Store network ids to which the publisher site belongs to
$ads=array();
$slots=array(6,12,18,24); // Define the time slots for the campaign ads to run evenly throughout the day
$country=IP2Country($_SERVER['REMOTE_ADDR']);  // Necessary to run the ads limited for a particular geographic locations
# Fetch country id from DB
$SQL="SELECT countryId FROM `country` WHERE countries_iso_code_2='".$country."'";
$RS=mysql_query($SQL) or die();
if(mysql_num_rows($RS)){
$ROW=mysql_fetch_array($RS);
$countryId=$ROW[countryId];
}
//echo "Country :".$country;
$SQL_NET="SELECT  N.`networkId`,M.`adsiteId`, D.`allowNetwork`, AC.`categoryName`  FROM  `adspace_master` M, `adspace_details` D, `network_sites` N, `network_master` NM,  `adsite_master` SM,  `adcategories` AC WHERE M.`adspaceId`=D.`adspaceId` ";
$SQL_NET.=" AND D.`adspaceIdMd`='".$mdid."' ";
$SQL_NET.=" AND N.`siteId`=M.`adsiteId` ";
$SQL_NET.=" AND SM.`adsiteId`=M.`adsiteId` ";
$SQL_NET.=" AND AC.`adcategoryId`=SM.`adcategoryId` ";
$SQL_NET.=" AND NM.`networkId`=N.`networkId`";
$SQL_NET.=" AND NM.`networkType`=D.`adspaceType` ";
//$SQL_NET.=" AND (NM.`target_countries` LIKE '%".$country."%' OR NM.`target_countries` LIKE '".$country.",' OR NM.`target_countries` LIKE ',".$country."')";
$RS_NET=mysql_query($SQL_NET) or die("Error !! #1=>".mysql_error());
//echo "SQL_NET ".$SQL_NET."<br>";
//echo "<br>";
//echo "<br>";
while($ROW_NET=mysql_fetch_array($RS_NET)){
$nets[]=$ROW_NET[networkId];  // Store Network ids
$cats[]=$ROW_NET[categoryName]; // Store Category names of the site to which this adspace is belong to, actually it have same value for every loop
$sites[]=$ROW_NET[adsiteId];  // Store ids of the adsites, ctually it have same value for every loop
}
// ---------------------start

$SELECT_siteId = "select adsiteId from adspace_master where adspaceIdMd = '".$mdid."'";
$EXE_siteId= mysql_query($SELECT_siteId);
$ROW_siteId=mysql_fetch_array($EXE_siteId);

$siteId=$ROW_siteId['adsiteId'];

//echo $siteId;

$select_countryId_siteMaster="select adcountryId, adcategoryId from adsite_master where adsiteId = '".$siteId."'";
$exe_countryId_siteMaster=mysql_query($select_countryId_siteMaster);
$row_countryId_siteMaster=mysql_fetch_array($exe_countryId_siteMaster);

$categoryId_siteMaster=$row_countryId_siteMaster['adcategoryId'];
$countryId_siteMaster=$row_countryId_siteMaster['adcountryId'];

$select_site_category_name="select categoryName from adcategories where adcategoryId = '".$categoryId_siteMaster."'";
$exe_site_category_name=mysql_query($select_site_category_name);
$row_site_category_name=mysql_fetch_array($exe_site_category_name);

$site_category_name=$row_site_category_name['categoryName'];

//echo "<script>alert('".$countryId_siteMaster."')</script>";
$explode_countryId_siteMaster=explode(',',$countryId_siteMaster);
//echo "<script>alert('".$explode_countryId_siteMaster."')</script>";

$networkId_country='';
$SELECT_networkCountry="select * from network_country";
//echo $SELECT_networkCountry;
$EXE_networkCountry=mysql_query($SELECT_networkCountry);

while($ROW_networkCountry=mysql_fetch_array($EXE_networkCountry))
{
// echo "<script>alert('".$ROW_network_country['countryId']."')</script>"; 
	if(in_array($ROW_networkCountry['countryId'], $explode_countryId_siteMaster))
	{
		if($networkId_country=='')
		{
			$networkId_country=$ROW_networkCountry['networkId'];
		}
		else
		{
			$networkId_country.=",".$ROW_networkCountry['networkId'];
		}
	}
	else
	{
	}
}

$networkId_category='';
$SELECT_networkCategory="select * from network_ad_category where categoryId = '".$categoryId_siteMaster."'";
$EXE_networkCategory=mysql_query($SELECT_networkCategory);
while($ROW_networkCategory=mysql_fetch_array($EXE_networkCategory))
{
		if($networkId_category=='')
		{
			$networkId_category=$ROW_networkCategory['networkId'];
		}
		else
		{
			$networkId_category.=",".$ROW_networkCategory['networkId'];
		}
}


if($networkId_country=='')
{
	$networkIds=$networkId_category;
}
else
{
$networkIds=$networkId_country.",".$networkId_category;


$networkId_arr=explode(",",$networkIds);
$unique_networkId_arr=array_unique($networkId_arr);

$end_unique_networkId_arr=end($unique_networkId_arr);

$network_country_category='';
for($n=0;$n<$end_unique_networkId_arr;$n++)
{
	if($unique_networkId_arr[$n]!='')
	{
		if($network_country_category == '')
		{
			$network_country_category=$unique_networkId_arr[$n];
		}
		else
		{
			$network_country_category.=",".$unique_networkId_arr[$n];
		}
	}
	
}
$available_network_id=$network_country_category;

}

// ---------------------end



$SQL="";  // Unset previous value

  $SQL.=" SELECT AM.advertiseId, AM.adTitle_personal, AM.adTitle, AM.startDate, AM.falseId FROM advertise_details AD, adspace_details SD,advertise_master AM";
  $SQL.=" WHERE AD.advertiseId=AM.advertiseId AND SD.`allowNetwork`='Y' AND SD.adspaceIdMd='".$mdid."' ";
  $SQL.=" AND AM.startDate <= CURDATE()";
  $SQL.=" AND AM.advertiseStatus = 'Y' ";
  $SQL.=" AND AD.clicks_to_purchase  > AD.clicks_attempts";
  //$SQL.=" AND AD.networkId ='$net'";
  $SQL.=" AND AD.networkId IN (".$available_network_id.")";
  $SQL.=" UNION ";

$ctr=0;

    ?>
<?php

$SQLimp= trim($SQLimp,",");
//if($i)$RS=mysql_query($SQLimp) or die("Error #imp1");
//echo "<br>".$SQLimp;

// ************************************************************** starts RON(N)(24_07_09)**************************************************
$c=0;
$r=0;


# CMPAIGN MANAGER Custom network
#adsite_master => adcategoryId  //$SQL="SELECT * FROM `create_network`";  // match categories  find bids etc. #Find ads, adgroup, campaign for each custom network from above

### For RON=N
$SQL_N_RON =" SELECT CN_custom.network_id,CN_custom.bid,CN_custom.category,CN_custom.country FROM `adcampaign` CAMPAIGN, `adgroup` AGROUP, `adgroup_ad` AGROUPAD,  `create_network` CN_custom ";
$SQL_N_RON.=" WHERE CAMPAIGN.start_date <= CURDATE() AND CAMPAIGN.end_date >= CURDATE()";
//$SQL.=" AND C.start_hour <= '".date("H")."'' AND C.end_hour >= '".date("H")."'";
$SQL_N_RON.=" AND CAMPAIGN.approved = 'Y' AND CAMPAIGN.runn = 'Y'";  
$SQL_N_RON.=" AND CAMPAIGN.total_budget > CAMPAIGN.total_spent";
$SQL_N_RON.=" AND CAMPAIGN.daily_budget > CAMPAIGN.today_spent";
$SQL_N_RON.=" AND AGROUP.runn = 'Y' AND AGROUPAD.runn = 'Y'";
$SQL_N_RON.=" AND AGROUP.adgroup_daily_budget > AGROUP.today_spent";
$SQL_N_RON.=" AND AGROUP.`campaign_id`=CAMPAIGN.`campaign_id` ";
$SQL_N_RON.=" AND AGROUP.`network_type`='custom'";
$SQL_N_RON.=" AND AGROUP.`RON`='N'";
$SQL_N_RON.=" AND AGROUP.`adgroup_network`=CN_custom.`network_id` ";
$SQL_N_RON.=" AND AGROUPAD.`adgroup_id`=AGROUP.`adgroup_id` ";

//echo $SQL_N_RON;
$RS_N_RON=mysql_query($SQL_N_RON) or die(mysql_error());
$bid=array();
$custom_network_id_N_country='';
$custom_network_id_N_category='';
while($ROW_N_RON=mysql_fetch_array($RS_N_RON)){

$COUNTRY_CUSTOM_NETWORK = $ROW_N_RON['country'];
//echo "<script>alert('".$COUNTRY_CUSTOM_NETWORK."')</script>";
//echo "<script>alert('".$explode_countryId_siteMaster."')</script>";
$explode_COUNTRY_CUSTOM_NETWORK = explode(',',$COUNTRY_CUSTOM_NETWORK);
$count_explode_COUNTRY_CUSTOM_NETWORK=count($explode_COUNTRY_CUSTOM_NETWORK);

for($m=0;$m<$count_explode_COUNTRY_CUSTOM_NETWORK;$m++)
{
	if(in_array($explode_COUNTRY_CUSTOM_NETWORK[$m], $explode_countryId_siteMaster))
	{
	//echo "<script>alert('".$explode_COUNTRY_CUSTOM_NETWORK[$m]."')</script>";
		if($custom_network_id_N_country=='')
		{
			$custom_network_id_N_country=$ROW_N_RON['network_id'];
			//echo "<script>alert('hi--->".$custom_network_id_N_country."');</script>";
		}
		else
		{
			$custom_network_id_N_country.=",".$ROW_N_RON['network_id'];
			//echo "<script>alert('hello--->".$custom_network_id_N_country."');</script>";
		}
	}
	else
	{
		//echo "<script>alert('".$explode_COUNTRY_CUSTOM_NETWORK[$m]."')</script>";
	}
}

$CATEGORY_CUSTOM_NETWORK = $ROW_N_RON['category'];
$explode_CATEGORY_CUSTOM_NETWORK = explode(',',$CATEGORY_CUSTOM_NETWORK);
$count_explode_CATEGORY_CUSTOM_NETWORK=count($explode_CATEGORY_CUSTOM_NETWORK);
//echo "$explode_CATEGORY_CUSTOM_NETWORK--->";
 if(in_array($site_category_name,$explode_CATEGORY_CUSTOM_NETWORK))
 {
//echo "hi--->";
	if($custom_network_id_N_category=='')
	{
		$custom_network_id_N_category=$ROW_N_RON['network_id'];
		//echo "<script>alert('xxxx----->".$custom_network_id_N_category."')</script>";
	}
	else
	{
		$custom_network_id_N_category.=",".$ROW_N_RON['network_id'];
		//echo "<script>alert('yyy------>".$custom_network_id_N_category."')</script>";
	}
 }
 else
 {
 }
//echo "<script>alert('".$CATEGORY_CUSTOM_NETWORK."')</script>";
$bid[$ROW_N_RON[0]]=$ROW_N_RON[1];
}

// -----------
if($custom_network_id_N_country=='')
{
	$networkIds_campaign_custom=$custom_network_id_N_category;
}
else
{
$networkIds_campaign_custom=$custom_network_id_N_country.",".$custom_network_id_N_category;


$networkId_arr_campaign_custom=explode(",",$networkIds_campaign_custom);
$unique_networkId_arr_campaign_custom=array_unique($networkId_arr_campaign_custom);

$end_unique_networkId_arr_campaign_custom=end($unique_networkId_arr_campaign_custom);

$network_country_category_campaign_custom='';
for($y=0;$y<$end_unique_networkId_arr_campaign_custom;$y++)
{
	if($unique_networkId_arr_campaign_custom[$y]!='')
	{
		if($network_country_category_campaign_custom == '')
		{
			$network_country_category_campaign_custom=$unique_networkId_arr_campaign_custom[$y];
		}
		else
		{
			$network_country_category_campaign_custom.=",".$unique_networkId_arr_campaign_custom[$y];
		}
	}
	
}
$available_network_id_campaign_custom=$network_country_category_campaign_custom;

}
//echo "<script>alert('".$available_network_id_campaign_custom."')</script>";
// ---------

## Determine the AD with the specific bid will goes to which grade site
$CNS=array_keys($bid);
if(count($bid)==1){
   $CN=$CNS[0];
}else if(count($bid)>1){
switch ($ctr_grade) {
case 'A':
   $CN=$CNS[0];
   break;
case 'B':
   $CN=$CNS[1];
   break;
case 'C':
  if(count($bid)>2){
   $CN=$CNS[2];
   }
   break;
case 'D':
   if(count($bid)>3){
   $CN=$CNS[3];
   }
   break;
case 'E':
   if(count($bid)>4){
   $CN=array_slice($CNS,4);
   }
   break;
}
 }
//$CN=array_slice($CNS,1);
//echo "CN: ".$CN;

$SQL.=" SELECT AGAD.adgroup_ad_id, AGAD.ad_description, AGAD.heading, C.start_date, AGAD.adgroup_ad_id FROM `adcampaign` C, `adgroup` AG, `adgroup_ad` AGAD,  `create_network` CN ";
$SQL.=" WHERE C.start_date <= CURDATE() AND C.end_date >= CURDATE()";
//$SQL.=" AND C.start_hour <= '".date("H")."'' AND C.end_hour >= '".date("H")."'";
$SQL.=" AND C.approved = 'Y' AND C.runn = 'Y'";  
$SQL.=" AND C.total_budget > C.total_spent";
$SQL.=" AND C.daily_budget > C.today_spent";
$SQL.=" AND AG.runn = 'Y' AND AGAD.runn = 'Y'";
$SQL.=" AND AG.adgroup_daily_budget > AG.today_spent";
$SQL.=" AND AG.`campaign_id`=C.`campaign_id` ";
$SQL.=" AND AG.`network_type`='custom'";
$SQL.=" AND AG.`RON`='N'";
$SQL.=" AND AG.`adgroup_network` IN (".$available_network_id_campaign_custom.") ";
$SQL.=" AND AG.`adgroup_network`=CN.`network_id` ";
$SQL.=" AND AGAD.`adgroup_id`=AG.`adgroup_id` ";
// if(is_array($CN))$SQL.=" AND CN.`network_id` IN (".implode(",",$CN).")";   // In initial run of the site this sql checking should be ommited as then CTR wiil low or even unavailable 
// else $SQL.=" AND CN.`network_id`='".$CN."'"; 
$SQL.=" UNION ";
// ************************************************************** ends RON(N) (24_07_09)**************************************************


// ************************************************************* starts RON(Y) (24_07_09)******************************************************

## RON=Y
$SQL_Y_RON =" SELECT CN.network_id,CN.bid FROM `adcampaign` C, `adgroup` AG, `adgroup_ad` AGAD,  `create_network` CN ";
$SQL_Y_RON.=" WHERE C.start_date <= CURDATE() AND C.end_date >= CURDATE()";
//$SQL.=" AND C.start_hour <= '".date("H")."'' AND C.end_hour >= '".date("H")."'";
$SQL_Y_RON.=" AND C.approved = 'Y' AND C.runn = 'Y'";  
$SQL_Y_RON.=" AND C.total_budget > C.total_spent";
$SQL_Y_RON.=" AND C.daily_budget > C.	today_spent";
$SQL_Y_RON.=" AND AG.runn = 'Y' AND AGAD.runn = 'Y'";
$SQL_Y_RON.=" AND AG.adgroup_daily_budget > AG.today_spent";
$SQL_Y_RON.=" AND AG.`campaign_id`=C.`campaign_id` ";
$SQL_Y_RON.=" AND AG.`network_type`='custom'";
$SQL_Y_RON.=" AND AG.`RON`='Y'";
$SQL_Y_RON.=" AND AG.`adgroup_network`=CN.`network_id` ";
$SQL_Y_RON.=" AND AGAD.`adgroup_id`=AG.`adgroup_id` ";
//$SQLron.=" AND (CN.`category` LIKE '%".$cats[0]."%' OR CN.`category` LIKE '".$cats[0].",' OR CN.`category` LIKE ',".$cats[0]."')"; // Category checking not required for RON=Y

$RS_Y_RON=mysql_query($SQL_Y_RON) or die(mysql_error());
$bidron=array();
while($ROW_Y_RON=mysql_fetch_array($RS_Y_RON)){
$bidron[$ROW_Y_RON[0]]=$ROW_Y_RON[1];
}
## Determine the AD with the specific bid will goes to which grade site
$CNSron=array_keys($bidron);
if(count($bidron)==1){
   $CNron=$CNS[0];
}else if(count($bidron)>1){
switch ($ctr_grade) {
case 'A':
   $CNron=$CNSron[0];
   break;
case 'B':
   $CNron=$CNSron[1];
   break;
case 'C':
  if(count($bidron)>2){
   $CNron=$CNSron[2];
   }
   break;
case 'D':
   if(count($bidron)>3){
   $CNron=$CNSron[3];
   }
   break;
case 'E':
   if(count($bidron)>4){
   $CNron=array_slice($CNSron,4);
   }
   break;
}
 }

$SQL.=" SELECT AGAD.adgroup_ad_id, AGAD.ad_description, AGAD.heading, C.start_date, AGAD.adgroup_ad_id FROM `adcampaign` C, `adgroup` AG, `adgroup_ad` AGAD,  `create_network` CN ";
$SQL.=" WHERE C.start_date <= CURDATE() AND C.end_date >= CURDATE()";
//$SQL.=" AND C.start_hour <= '".date("H")."'' AND C.end_hour >= '".date("H")."'";
$SQL.=" AND C.approved = 'Y' AND C.runn = 'Y'";  
$SQL.=" AND C.total_budget > C.total_spent";
$SQL.=" AND C.daily_budget > C.	today_spent";
$SQL.=" AND AG.runn = 'Y' AND AGAD.runn = 'Y'";
$SQL.=" AND AG.adgroup_daily_budget > AG.today_spent";
$SQL.=" AND AG.`campaign_id`=C.`campaign_id` ";
$SQL.=" AND AG.`network_type`='custom'";
$SQL.=" AND AG.`RON`='Y'";
$SQL.=" AND AG.`adgroup_network`=CN.`network_id` ";
$SQL.=" AND AGAD.`adgroup_id`=AG.`adgroup_id` ";
//$SQL.=" AND (CN.`category` LIKE '%".$cats[0]."%' OR CN.`category` LIKE '".$cats[0].",' OR CN.`category` LIKE ',".$cats[0]."')"; // Category checking not required for RON=Y
// if(is_array($CNron))$SQL.=" AND CN.`network_id` IN (".implode(",",$CNron).")";   // In initial run of the site this sql checking should be ommited as then CTR wiil low or even unavailable 
// else $SQL.=" AND CN.`network_id`='".$CNron."'"; 
$SQL.=" UNION ";
## End RON=Y



// ************************************************************* Ends RON(Y) (24_07_09)******************************************************


$SQL.=" SELECT AGAD.adgroup_ad_id, AGAD.ad_description, AGAD.heading, C.start_date, AGAD.adgroup_ad_id FROM `adcampaign` C, `adgroup` AG, `adgroup_ad` AGAD ";
$SQL.=" WHERE C.start_date <= CURDATE() AND C.end_date >= CURDATE()";
//$SQL.=" AND C.start_hour <= '".date("H")."'' AND C.end_hour >= '".date("H")."'";
$SQL.=" AND C.approved = 'Y' AND C.runn = 'Y'";
$SQL.=" AND C.total_budget > C.total_spent";
$SQL.=" AND C.daily_budget > C.today_spent";
#$SQL.=" AND AG.runn = 'Y' AND AGAD.runn = 'Y'";
$SQL.=" AND AG.adgroup_daily_budget > AG.today_spent";
$SQL.=" AND AG.`campaign_id`=C.`campaign_id` ";
$SQL.=" AND AG.`network_type`='direct' ";
$SQL.=" AND AG.`RON`='N'";
$SQL.=" AND AG.`adgroup_network` IN (".$available_network_id.") ";
$SQL.=" AND AGAD.`adgroup_id`=AG.`adgroup_id` ";
$SQL.=" ORDER BY `startDate` ";
$SQL.=" LIMIT 0,".$adsno." ";

//echo $SQL;

$RS=mysql_query($SQL) or die(mysql_error()." ".$SQL);
# Inser into track for every visit
// $SQLimp_camp_direct="INSERT INTO `advertise_impression_trac` (adsiteId,adspaceId,campaign_ad,adgroup_ad_id,adgroup_id,campaign_id,client_IP,country,visit_time)VALUES";
// $i=0;
$TOTAL_ADS=mysql_num_rows($RS);
while($ROW=mysql_fetch_array($RS)){

if($ROW['falseId']!='')
{
	$SELECT_campaign_details_ad="SELECT Camp.*,Ad_gr.`network_type`,Ad_gr_ad.* FROM `adcampaign` Camp, `adgroup` Ad_gr, `adgroup_ad` Ad_gr_ad where Ad_gr_ad.adgroup_ad_id = '".$ROW['falseId']."' and Ad_gr_ad.adgroup_id = Ad_gr.adgroup_id and Ad_gr_ad.campaign_id = Camp.campaign_id";

	$EXE_campaign_details_ad=mysql_query($SELECT_campaign_details_ad);
	$ROW_campaign_details_ad= mysql_fetch_array($EXE_campaign_details_ad);
	

// $SQLimp_camp_direct.="(".$sites[0].",".$sp.",'Y',".$ROW_camp_direct[adgroup_ad_id].",".$ROW_camp_direct[adgroup_id].",".$ROW_camp_direct[campaign_id].",'".$_SERVER['REMOTE_ADDR']."','".$country."',NOW()),";
// $i++;

## Check whether to Run throughout the day 
if($ROW_campaign_details_ad[spend_memo]=='all_day'){
$flag=0;
foreach($slots as $k=>$v){
if(date("H")<=$v && $ROW_campaign_details_ad[today_spent]>=(($k+1)*$ROW_campaign_details_ad[daily_budget])/count($slots)) {
  $flag=1;
  break;
  }
}
reset($slots); // Reset the poiter of the array 
if($flag)continue;
// if(date("H")<=$slots[0] && $ROW[today_spent]>=(1*$ROW[daily_budget])/4) continue;
// if(date("H")<=$slots[1] && $ROW[today_spent]>=(2*$ROW[daily_budget])/4) continue;
// if(date("H")<=$slots[2] && $ROW[today_spent]>=(3*$ROW[daily_budget])/4) continue;
// if(date("H")<=$slots[3] && $ROW[today_spent]>=(4*$ROW[daily_budget])/4) continue;
}

## Determine the current campaign ad is whether target to custom network or predefined network
if($ROW_campaign_details_ad[network_type]=='direct')$N='D';
else if($ROW_campaign_details_ad[network_type]=='custom')$N='C';
////////////////////////////////////////////////////
}



 if($ROW[adTitle_personal]=="")$ROW[adTitle_personal]="No description avail..";
    $htmlstart='<table width="'.$totalWidth.'" height="'.$totalHeight.'" border="0" cellspacing="'.$cellSpacing.'"><tr>';
    $htmlend='</table>';
    if($c<=$cols){

if($ROW['falseId']=='')
{
	$html.='<td><table width="'.$width.'" height="'.$height.'" border="0" cellspacing="'.$cellSpacing.'" cellpadding="6" bgcolor="'.$backgroundColor.'">
               <tr><td align="center"><a href="'.$path.'wbk/?bk='.__randit().$ROW[advertiseId].__randit().'&s='.__randit().$sites[0].__randit().'&val='.$mdid.'" style="text-decoration:none;"><font color="'.$headerColor.'" style="font-family: '.$fontType.';">'.$ROW[adTitle].'</font><br><br><font color="'.$bodyColor.'" style="font-family: '.$fontType.';">'.$ROW[adTitle_personal].'</font></a></td></tr>
           </table></td>';
}
else
{

    $html.='<td><table width="'.$width.'" height="'.$height.'" border="0" cellspacing="'.$cellSpacing.'" cellpadding="6" bgcolor="'.$backgroundColor.'">
              <tr><td align="center"><a href="'.$path.'wbk/?a='.__randit().$ROW_campaign_details_ad[adgroup_ad_id].__randit().'&g='.__randit().$ROW_campaign_details_ad[adgroup_id].__randit().'&c='.__randit().$ROW_campaign_details_ad[campaign_id].__randit().'&s='.__randit().$sites[0].__randit().'&val='.$mdid.'&N='.$N.'" style="text-decoration:none;"><font color="'.$headerColor.'" style="font-family: '.$fontType.';">'.$ROW[adTitle].'</font><br><br><font color="'.$bodyColor.'" style="font-family: '.$fontType.';">'.$ROW[adTitle_personal].'</font></a></td></tr>
          </table></td>';
}
       $c++;
      }
    if($c==$cols){
//echo "<script>alert('".$c."')</script>";
    $html.='</tr><tr>';
    $r++;
    $c=0;
// 	if($r==$TOTAL_ADS)
// 	{
// 		$ads[]=htmlentities($htmlstart.$html.$htmlend);
// 	}
// 	else
// 	{
// 	}
	if($alignment=='horizontal')
	{
		$r=$TOTAL_ADS;
	}
	
    }

if($r==$TOTAL_ADS)
    {
    $ads[]=htmlentities($htmlstart.$html.$htmlend);
    //$html="";
    $r=0;
    }

    //if($r==$rows){
    if($c==$TOTAL_ADS)
    {
    $ads[]=htmlentities($htmlstart.$html.$htmlend);
    //$html="";
    $r=0;
    }


}
$SQLimp_camp_direct= trim($SQLimp_camp_direct,",");
if($i)$RS_camp_direct=mysql_query($SQLimp_camp_direct) or die("Error #imp2".mysql_error()."<br>".$SQLimp_camp_direct);
//echo "<br>".$SQLimp;
// echo "<pre>";
// print_r($ads);
// echo "</pre>";
//echo "<br>".$SQL;

// foreach($ads as $ad){
// echo html_entity_decode($ad);
// }

# Inser into track for every visit
$SQL="INSERT INTO `adspace_impression_trac` SET adspaceId='".$sp."',adsiteId='".$sites[0]."', client_IP='".$_SERVER['REMOTE_ADDR']."',country='".IP2Country($_SERVER['REMOTE_ADDR'])."',`visit_time`=NOW()";
$RS=mysql_query($SQL) or die("Error #imp3".mysql_error());






function __randit()
{
$chars = "1023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $ret = '' ;
	//generates 4 random numbers
    while ($i < 4) {
        $num = rand(1, 9);
        $tmp = substr($chars,$num,1);
        $ret = $ret . $tmp;
        $i++;
    }
return $ret;
}

function IP2Country($ipAddr)
{
$location = $ipAddr;
$q = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=rlerdorf&location='.rawurlencode($location);
$resp=file_get_contents($q);
$xml = simplexml_load_string($resp);
return $xml->Result[0]->Country;
}
//$ads=array('test','<table><tr><td>Abdul</td></tr></table>',2,3,4,5,6,7,8,9);
if(isset($_POST['Submit']) && $_POST['Submit']!= '')
{
    
   // echo $_POST['Submit'].'<br>';
    $ads=explode('@_@',$_POST['ads']);
    $counter=$_POST['counter'];
    $counter++;
   
    if($_POST['counter'] + (int)1 >= count($ads))
    {
        $counter=0;
    }
    //echo $counter;
    $ad=$ads[$counter];
}
else
{
    $counter=0;
    $ad=$ads[$counter];
}
?>

<form name="frm_ads" id="frm_ads" method="post" action="">
  <input type="hidden" name="counter" id="counter" value="<?php echo $counter;?>">
  <input type="hidden" name="ads" id="ads" value="<?php echo htmlentities(implode('@_@',$ads));?>">
  <input type="hidden" name="Submit" id="Submit" value="Submit">
</form>
<div>
    <?php echo html_entity_decode($ad); ?>
</div>

<script>
setTimeout("SUBMITfunction();",500);
function SUBMITfunction()
{
	//document.frm_ads.ads.filters.blendTrans.Play();
	//document.images.fetchAdCodeImg.filters.blendTrans.Play();
    document.getElementById("frm_ads").submit();
}
</script>